package com.crane.common.framework.shiro;

import com.crane.common.core.dto.SessParty;
import com.crane.common.core.dto.SessUser;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.exception.BizException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * @author zhenxing.pi
 */
public class ShiroUtils {

    private static String partyKey = "userParty";

    public static Session getSession() {

        Session session = SecurityUtils.getSubject().getSession(false);
        if (null == session) {
            throw new AppException(BasicErrorCode.SESSION_TIMEOUT);
        }
        return session;
    }

    public static Session getNewSession() {
        return SecurityUtils.getSubject().getSession(true);
    }

    public static Subject getSubject() throws BizException {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            throw new AppException(BasicErrorCode.SESSION_TIMEOUT);
        }
        return subject;
    }

    public static SessUser getUser() throws BizException {
        return (SessUser) getSubject().getPrincipal();
    }

    public static Long getUserId() throws BizException {
        return getUser().getUserId();
    }


    public static void setParty(SessParty party) throws BizException {
        getSession().setAttribute(partyKey, party);
    }

    public static SessParty getParty() throws BizException {
        Object obj = getSession().getAttribute(partyKey);
        if (null == obj) {
            return null;
        }
        return (SessParty) obj;
    }


    public static void setSessionAttribute(Object key, Object value) throws BizException {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) throws BizException {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

}
